package it.unibz.ti2.internetPizzeria.servlets;

import it.unibz.ti2.internetPizzeria.dao.OrderDAO;
import it.unibz.ti2.internetPizzeria.entities.Order;
import it.unibz.ti2.internetPizzeria.utils.OrderUtil;
import it.unibz.ti2.internetPizzeria.utils.ServletUtil;
import it.unibz.ti2.internetPizzeria.webAttributes.OrderInfo;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Changing orders' statuses from StatusAwaitingPreparation to StatusInPreparation and from StatusInPreparation to StatusReadyToDeliver.
 */
public class OrdersInPreparation extends HttpServlet{

	private static final long serialVersionUID = 8223867891651377897L;

	protected void doGet(HttpServletRequest arg0, HttpServletResponse arg1) throws ServletException, IOException {
		this.doPost(arg0, arg1);
	}

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		OrderDAO orderDAO = null;
		try {
			orderDAO = new OrderDAO();			
			orderDAO.openSession();
			
			Object changeToInPreparationParam = request.getParameter("ordersInPreparationSubmit");
			Object changeToReadyToDeliverParam = request.getParameter("ordersPreparedSubmit");
			String[] orderIds = request.getParameterValues("orderId");
			if (orderIds != null){
				for (int i = 0; i < orderIds.length; i++) {
					Order order = orderDAO.getOrder(Long.parseLong(orderIds[i]));
					if (changeToInPreparationParam != null){
						order.setStatus(Order.StatusInPreparation);
					} else if (changeToReadyToDeliverParam != null){
						order.setStatus(Order.StatusReadyToDeliver);
					}
					orderDAO.update(order);
				}
			}			
			
			List<Order> ordersReadyToPrepare = orderDAO.getOrders(Order.StatusAwaitingPreparation);
			List<Order> ordersInPreparation = orderDAO.getOrders(Order.StatusInPreparation);
			
			List<OrderInfo> orderInfosReadyToPrepare = OrderUtil.getOrderInfos(ordersReadyToPrepare);
			List<OrderInfo> orderInfosInPreparation = OrderUtil.getOrderInfos(ordersInPreparation);
			
			request.setAttribute("orderInfosReadyToPrepare", orderInfosReadyToPrepare);
			request.setAttribute("orderInfosInPreparation", orderInfosInPreparation);
			
			ServletUtil.redirect(request, response, "/ordersPreparation.jsp");
		} catch (Exception ex) {			
			ex.printStackTrace();
		} finally {
			if (orderDAO != null){
				orderDAO.closeSession();
			}
		}
		
	}
	
}
